package com.tarena.luban.demo.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;


public class MyFilter02 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("请求经过了myFilter02");
        //使用响应对象 将自定义的字符串输出返回,后续流程(downStream) 不在执行
        //拿到响应对象
        ServerHttpResponse response = exchange.getResponse();
        //准备一个拦截输出的字符串 JsonResult
        String result="你被拦截了";
        //告诉前端 设置响应头Content-Type: application/json;charset=utf-8 谷歌 火狐 默认补充charset ie 苹果
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        //return response.writeWith(Mono.fromSupplier(()-> response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8))));
        //响应最终输出的二进制流
        byte[] bytes=result.getBytes(StandardCharsets.UTF_8);
        //从response获取一个缓冲流对象,包裹二进制
        DataBufferFactory dataBuffer = response.bufferFactory();
        DataBuffer wrap = dataBuffer.wrap(bytes);
        //response要参照Mono的格式 将dataBuffer做最终输出
        Mono<DataBuffer> monoResult = Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return wrap;
            }
        });
        return response.writeWith(monoResult);
    }

    @Override
    public int getOrder() {
        return 200;
    }
}
